<?php
namespace app\admin\model;
use think\Model;
class Article extends Model
{
    protected static function init()
    {
        //新增前
        Article::event('before_insert',function ($data){
            if ($_FILES['thumb']['tmp_name']){
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public' . DS .'static/uploads');
                if ($info){
//                    $thumb=ROOT_PATH . 'public' . DS .'uploads'.'/'.$info->getSaveName();
                    $thumb = '/static/uploads'.'/'.$info->getSaveName();
                    $data['thumb'] = $thumb;
                }
            }
        });
        //更新前
        Article::event('before_update',function ($data){
            if ($_FILES['thumb']['tmp_name']){
                $arts = Article::find($data->id);
//                echo $_SERVER['DOCUMENT_ROOT'];die;
                $thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
                if (file_exists($thumbpath)){
                    @unlink($thumbpath);
                }
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public' . DS .'static/uploads');
                if ($info){
                    $thumb = '/static/uploads'.'/'.$info->getSaveName();
                    $data['thumb'] = $thumb;
                }
            }
        });
        //删除前
        Article::event('before_delete',function ($data){
            $arts = Article::find($data->id);
            $thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
            if (file_exists($thumbpath)){
                @unlink($thumbpath);
            }
        });
    }

    public function cate(){
        //一个栏目可以对应多篇文章，所以是一对多的模型
        //与之相对的 多篇文章对应一个栏目
        //定义相对的关联
        return $this->belongsTo('cate','cateid');//cate表要和article表的cateid关联，cateid为外键
        //默认外键是  表名_id
    }
}

